package com.yjt.fresh.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.activity.AtyAfterSale;
import com.yjt.fresh.activity.AtyCart;
import com.yjt.fresh.activity.AtyCommentCenter;
import com.yjt.fresh.activity.AtyLogin;
import com.yjt.fresh.activity.AtyMassages;
import com.yjt.fresh.activity.AtyMyAddress;
import com.yjt.fresh.activity.AtyMyCollection;
import com.yjt.fresh.activity.AtyMyCoupon;
import com.yjt.fresh.activity.AtyMyOrder;
import com.yjt.fresh.activity.AtyMyScore;
import com.yjt.fresh.activity.AtyMyWallet;
import com.yjt.fresh.activity.AtyOpenStore;
import com.yjt.fresh.activity.AtyPersonalInfo;
import com.yjt.fresh.activity.AtySetting;
import com.yjt.fresh.adpater.AdpRvMainAtyPersonalPageOrder;
import com.yjt.fresh.api.ApiGetUserInfo;
import com.yjt.fresh.base.BaseSimpleFragment;
import com.yjt.fresh.bean.BeanHomePage;
import com.yjt.fresh.bean.BeanUserInfo;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.CommonsToolsHelper;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.FullyLinearLayoutManager;
import com.yjt.fresh.widget.SpaceItemDecorationHorizontal;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import jp.wasabeef.glide.transformations.CropCircleTransformation;


/**
 * 个人信息
 * Created by mcc on 2018/6/10.
 */

public class FrgPersonal extends BaseSimpleFragment {
    private static final int REQUEST_CODE = 1009;
    @BindView(R.id.rv_app_atymain_frg_personalPage)
    RecyclerView mRv;
    @BindView(R.id.rl_app_atymain_frg_personal_myScore)
    RelativeLayout mRlMyScore;
    @BindView(R.id.rl_app_atymain_frg_personal_myCoupon)
    RelativeLayout mRlMyCoupon;
    @BindView(R.id.rl_app_atymain_frg_personal_myAddress)
    RelativeLayout mRlMyAddress;
    @BindView(R.id.rl_app_atymain_frg_personal_myCollection)
    RelativeLayout mRlMyCollection;
    @BindView(R.id.rl_app_atymain_frg_personal_myComment)
    RelativeLayout mRlMyComment;
    @BindView(R.id.rl_app_atymain_frg_personal_openStore)
    RelativeLayout mRlOpenStore;
    @BindView(R.id.ivAppAtyMainFrgPersonalSetting)
    ImageView mIvSetting;
    @BindView(R.id.ivAppAtyMainFrgPersonalUserPhoto)
    ImageView mIvUserPhoto;
    @BindView(R.id.tvAppAtyMainFrgPersonalUserName)
    TextView mTvUserName;
    @BindView(R.id.tvAppAtyMainFrgPersonalUserID)
    TextView mTvUserID;
    @BindView(R.id.llAppAtyMainFrgPersonalUserInfo)
    LinearLayout mLUserInfo;
    @BindView(R.id.rlAppAtyMainFrgPersonalMyOrder)
    RelativeLayout mRlMyOrder;
    @BindView(R.id.tvAppFrgPersonalNewMassageCount)
    TextView mTvNewMassageCount;
    @BindView(R.id.flAppFrgPersonalMassage)
    FrameLayout mFlMassage;
    @BindView(R.id.rlAppFrgPersonalNewMassageCount)
    RelativeLayout mRlNewMassageCount;
    @BindView(R.id.ivAppAtyMainFrgPersonalSex)
    ImageView mIvSex;
    @BindView(R.id.rl_app_atymain_frg_personal_cart)
    RelativeLayout mRlCart;
    @BindView(R.id.tv_app_atymain_frg_personal_wallet_money)
    TextView mTvWalletMoney;
    @BindView(R.id.rl_app_atymain_frg_personal_wallet)
    RelativeLayout mRlWallet;
    private LocalBroadcastManager mBroadcastManager;
    private AdpRvMainAtyPersonalPageOrder mAdpOrder;

    @Override
    protected int getContentView() {
        return R.layout.app_atymain_frg_personal;
    }

    @Override
    protected void initView(Bundle savedInstanceState, View view) {
        ButterKnife.bind(this, view);
        if (PreferenceManager.getInstance().getIsLogin()) {
            BeanUserInfo userInfo = PreferenceManager.getInstance().getUserInfo();
            Glide.with(mContext)
                    .load(userInfo.getLOGO_IMG())
                    .placeholder(R.mipmap.f1_ic_06)
                    .bitmapTransform(new CropCircleTransformation(getContext()))
                    .into(mIvUserPhoto);
            mTvUserID.setText("ID:" + userInfo.getAPPUSER_ID());
            mTvUserName.setText(userInfo.getNICKNAME());
        }
    }


    @Override
    protected void initEvents() {
        initRv();
        initClick();
        initBroadCast();
        if (PreferenceManager.getInstance().getIsLogin()) {
            getUserInfo();
        }
    }

    private void initRv() {
        FullyLinearLayoutManager categoryLayoutManager = new FullyLinearLayoutManager(mContext);
        categoryLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRv.setLayoutManager(categoryLayoutManager);
        List<BeanHomePage> beanHomePages = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            beanHomePages.add(new BeanHomePage());
        }
        int windowWidth = CommonsToolsHelper.getWindowWidth(mContext);

        int space = (windowWidth - CommonsToolsHelper.dip2px(mContext, 40) - CommonsToolsHelper.dip2px(mContext, 65 * 5)) / 4;
        mRv.addItemDecoration(new SpaceItemDecorationHorizontal(space));
        mAdpOrder = new AdpRvMainAtyPersonalPageOrder(R.layout.app_recycle_item_personalpage_order, beanHomePages);
        mRv.setAdapter(mAdpOrder);
    }


    private void initClick() {
        mRlWallet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyMyWallet.class);
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    toLogin();
                }
            }
        });
        mRlCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyCart.class);
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    toLogin();
                }
            }
        });
        mFlMassage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyMassages.class);
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    login();
                }
            }
        });
        mIvSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtySetting.class);
                startActivity(intent);
            }
        });
        mLUserInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyPersonalInfo.class);
                    startActivityForResult(intent, MyConstants.UPDATE_USER_INFO);
                } else {
                    Intent intent = new Intent(mContext, AtyLogin.class);
                    startActivity(intent);
                }
            }
        });
        mRlMyScore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyMyScore.class);
                    startActivity(intent);
                } else {
                    login();
                }
            }
        });

        mRlMyCoupon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyMyCoupon.class);
                    startActivity(intent);
                } else {
                    login();
                }
            }
        });

        mRlMyAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyMyAddress.class);
                    startActivity(intent);
                } else {
                    login();
                }
            }
        });

        mRlMyCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyMyCollection.class);
                    startActivity(intent);
                } else {
                    login();
                }
            }
        });

        mRlMyComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyCommentCenter.class);
                    startActivity(intent);
                } else {
                    login();
                }

            }
        });

        mRlMyOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    Intent intent = new Intent(mContext, AtyMyOrder.class);
                    intent.putExtra(MyConstants.POSITION, -1);
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    login();
                }
            }
        });

        mAdpOrder.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (PreferenceManager.getInstance().getIsLogin()) {
                    if (position == 4) {
                        Intent intent = new Intent(mContext, AtyAfterSale.class);
                        startActivityForResult(intent, REQUEST_CODE);
                    } else {
                        Intent intent = new Intent(mContext, AtyMyOrder.class);
                        intent.putExtra(MyConstants.POSITION, position);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                } else {
                    login();
                }
            }
        });
    }

    private void login() {
        Intent intent = new Intent(mContext, AtyLogin.class);
        startActivity(intent);
    }

    /*注册广播接收登录或者注销信息*/
    private void initBroadCast() {
        IntentFilter intentFilter = new IntentFilter(MyConstants.LOGIN_LOCAL_BROADCAST);
        mBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        mBroadcastManager.registerReceiver(mLocalReceiver, intentFilter);
    }

    BroadcastReceiver mLocalReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int optType = intent.getIntExtra(MyConstants.JUMP_TYPE, 0);
            if (optType == MyConstants.LOGIN) {
                getUserInfo();
                Glide.with(mContext)
                        .load(PreferenceManager.getInstance().getUserInfo().getLOGO_IMG())
                        .placeholder(R.mipmap.default_user_img)
                        .bitmapTransform(new CropCircleTransformation(getContext()))
                        .into(mIvUserPhoto);
                mIvSex.setVisibility(View.VISIBLE);
                mTvUserName.setText(PreferenceManager.getInstance().getUserInfo().getNICKNAME());
                mTvUserID.setText("ID:" + PreferenceManager.getInstance().getUserInfo().getAPPUSER_ID());

            } else if (optType == MyConstants.LOGOUT) {
                mRlNewMassageCount.setVisibility(View.GONE);
                mIvSex.setVisibility(View.GONE);
                mIvUserPhoto.setImageResource(R.mipmap.default_user_img);
                mTvUserName.setText("点击登录");
                mTvUserID.setText("");
                mAdpOrder.setIsLogin(false);
            }
        }
    };
    private BeanUserInfo mBeanUserInfo;
    HttpOnNextListener<BeanUserInfo> mUserInfoListener = new HttpOnNextListener<BeanUserInfo>() {
        @Override
        public void onNext(BeanUserInfo beanUserInfo) {
            PreferenceManager.getInstance().setUserInfo(beanUserInfo);
            mBeanUserInfo = beanUserInfo;
            mRlOpenStore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, AtyOpenStore.class);
                    intent.putExtra(MyConstants.IS_APPLY, mBeanUserInfo.getISAPPLY());
                    startActivityForResult(intent, REQUEST_CODE);
                }
            });
            mAdpOrder.setUserInfo(beanUserInfo);
            if (Integer.valueOf(beanUserInfo.getNEWMSGCOUNT()) > 0) {
                mRlNewMassageCount.setVisibility(View.VISIBLE);
                mTvNewMassageCount.setText(beanUserInfo.getNEWMSGCOUNT());
            } else {
                mRlNewMassageCount.setVisibility(View.GONE);
            }
            mTvUserID.setText("ID:" + beanUserInfo.getAPPUSER_ID());
            if (beanUserInfo.getNICKNAME() != null) {
                mTvUserName.setText(beanUserInfo.getNICKNAME());
                if ("男".equals(beanUserInfo.getSEX())) {
                    mIvSex.setImageResource(R.mipmap.f_ic_04);
                } else if ("女".equals(beanUserInfo.getSEX())) {
                    mIvSex.setImageResource(R.mipmap.f_ic_05);
                }
            }

            PreferenceManager.getInstance().setRestMoney(Double.valueOf(beanUserInfo.getYU_MONEY()));
            mTvWalletMoney.setText(beanUserInfo.getYU_MONEY()+"元");

        }

        @Override
        public void onReLogin() {

        }

    };

    private void getUserInfo() {
        ApiGetUserInfo apiGetUserInfo = new ApiGetUserInfo(mUserInfoListener, mContext, true, false, true);
        apiGetUserInfo.setSession_id(PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        HttpManager.getInstance().doHttpDeal(apiGetUserInfo);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MyConstants.UPDATE_USER_INFO) {
            BeanUserInfo userInfo = PreferenceManager.getInstance().getUserInfo();
            Glide.with(mContext)
                    .load(userInfo.getLOGO_IMG())
                    .placeholder(R.mipmap.f1_ic_06)
                    .bitmapTransform(new CropCircleTransformation(getContext()))
                    .into(mIvUserPhoto);
            mTvUserName.setText(userInfo.getNICKNAME());
            if (userInfo.getSEX() != null) {
                if ("男".equals(userInfo.getSEX())) {
                    mIvSex.setImageResource(R.mipmap.f_ic_04);
                } else {
                    mIvSex.setImageResource(R.mipmap.f_ic_03);
                }
            }
        }
        if (PreferenceManager.getInstance().getIsLogin()) {
            getUserInfo();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mBroadcastManager.unregisterReceiver(mLocalReceiver);
    }


}
